'use strict';

/**
 * connection.js change from model.js 13.5.2015
 * instead of init the model inside the index.js file
 * we could take care of that here. Then just export a db instance back.
 * This way we further abstract away the tie between app and database backend
 * 21.9.2015 - since this is now a static file, we are moving it to the lib folder
 */

var // config = require('./config'),
    _ = require('lodash'),
    // umzug = require('umzug'), // https://github.com/sequelize/umzug <-- for migration [TODO]
    chalk = require('chalk');
////////////////////////////////
// Bootstrap db connection    //
////////////////////////////////

// export it
module.exports = function(config)
{

    var connections = {};
    // placeholder for clients, it seems dump but it makes it clear what the heck we are calling
    var mongoose, sequelize , cradle , redis;

    /**
     * quick I am dead func
     */
    var die = function(msg , e)
    {
        msg = msg || 'Connection error: ';
        e = e || '';
        console.log(chalk.red(msg , e));
        process.exit(-1);
    };

    if (_.isUndefined(config.db.default)) {
        die('Database configuration error, missing default profile!');
    }
    /**
     14.9.2015 - breaking change
     support multiple database connection profile
     the default is call 'default' we set that one up, then running through the rest of the config.db.XX to setup connection in a pool
    **/
    _.each(config.db , function(conf , name)
    {
        switch (conf.type) {
            case 'NOSQL':
                switch (conf.driver) {
                    case 'mongodb':
                        if (_.isUndefined(mongoose)) {
                            mongoose = require('mongoose');
                        }
                        // 16.8.2015 change from connection -> createConnection
                        connections[name] = mongoose.createConnection(conf.uri, conf.options, function(err) {
                            if (err) {
                                console.error(chalk.red('Could not connect to MongoDB!'));
                                console.log(chalk.red(err));
                            }
                        });
                        /**
                         * listening to error, is this a double call? see above line
                         */
                        mongoose.connection.on('error', function(err)
                        {
                            die('MongoDB connection error: ' , err);
                        });
                    break;
                    case 'couchdb':
                        if (_.isUndefined(cradle)) {
                            cradle = require('cradle');
                        }
                        connections[name] = new(cradle.Connection)(conf.uri , conf.options.port, {
                            cache: conf.options.cache || true,
                            raw: conf.options.raw || false,
                            forceSave: conf.options.forceSave || true
                        });
                    break;
                    case 'redis':
                        if (_.isUndefined(redis)) {
                            redis = require('redis');
                        }
                        // 'redis://user:pass@host:port' == 6379, '127.0.0.1'
                        connections[name] = redis.createClient(conf.uri , conf.options);
                        connections[name].on("error", function (err)
                        {
                            die("Redis connection Error " , err);
                        });
                    break;
                    default:
                        // nothing todo
                }
            break;
            case 'RDBMS':
                if (_.isUndefined(sequelize)) {
                    sequelize = require('sequelize');
                }
                try {
                    connections[name] = new Sequelize(conf.uri , conf.options);
                } catch(e) {
                    die('Database connection error:' , e);
                }
            break;
            default:
                // nothing here at the moment, nothing coming soon
        }
    });
    return connections;
};

// -- EOF --
